'use strict'
var mysql = require('mysql');
var http = require('http');
var url = require('url');
var fs = require('fs');
var formidable = require('formidable'); //上传文件插件
var express = require('express');
var app = module.exports = express();
var qs = require('querystring');
var router = express.Router();
var path = require('path');
var os = require('os');
var async = require('async');
//var config = require('config');

var conn = mysql.createConnection({
	host: '127.0.0.1',
	user: 'root',
	password: '',
	database: 'blog'
		//port: 3306
});
conn.connect();

//注册服务
http.createServer(function(req, res) {
	res.writeHeader(200, {
		'Content-Type': 'text/html',
		'Access-Control-Allow-Origin': '*'
	});

	if(req.method.toUpperCase() == 'POST') {
		var uploadPath = path.posix.join( //path.posix.join类似于path.join，兼容posix而已
			path.resolve(__dirname, 'pic') //使用__dirname变量获取当前模块文件所在目录，将pic接入_dirname后面
		);
		var arg = url.parse(req.url, true);

		if(true) {
			if(!fs.existsSync(uploadPath)) { //fs.existsSync用于检测文件路径
				fs.mkdirSync(uploadPath); //fs.mkdirSync以异步的方式创建文件目录
			}
			var form = new formidable.IncomingForm(); //创建上传表单
			form.encoding = 'utf-8'; //设置编辑
			form.uploadDir = uploadPath; //设置上传目录
			form.keepExtensions = true; //保留后缀
			form.maxFieldsSize = 2 * 1024 * 1024; //文件大小
			form.type = true;
			var displayUrl;
			form.parse(req, function(err, fields, files) { //form通过parse方法提交图片，fields可以通过键值对获取值
				//				console.log(files);
				var save_path = "";
				for(var key in files) {
					console.log(files[key]); //区别 upload+后缀数字

					if(err) {
						res.send(err);
						return;
					}
					var extName = ''; //后缀名
					switch(files[key].type) {
						case 'image/pjpeg':
							extName = 'jpg';
							break;
						case 'image/jpeg':
							extName = 'jpg';
							break;
						case 'image/png':
							extName = 'png';
							break;
						case 'image/x-png':
							extName = 'png';
							break;
					}
					if(extName.length === 0) {
						res.send({
							code: 202,
							msg: '只支持png和jpg格式图片'
						});
						return;
					} else {
						var avatarName = '/' + Date.now() + Math.floor(Math.random() * 10000 + 1) + '.' + extName;
						var newPath = form.uploadDir + avatarName;
						//console.log('blog'+'/'+'ServerJS'+'/'+'pic'+avatarName);  //手动合并路径
						fs.renameSync(files[key].path, newPath); //重命名

						var save_single_path = '/' + 'blog' + '/' + 'ServerJS' + '/' + 'pic' + avatarName;
						save_path = save_path + save_single_path + ',';
					}
				}
				save_path = save_path.substring(0, save_path.length - 1);
				console.log(save_path);

				//				if(err) {
				//					res.send(err);
				//					return;
				//				}
				//				var extName = ''; //后缀名
				//				switch(files.upload0.type) {
				//					case 'image/pjpeg':
				//						extName = 'jpg';
				//						break;
				//					case 'image/jpeg':
				//						extName = 'jpg';
				//						break;
				//					case 'image/png':
				//						extName = 'png';
				//						break;
				//					case 'image/x-png':
				//						extName = 'png';
				//						break;
				//				}
				//				if(extName.length === 0) {
				//					res.send({
				//						code: 202,
				//						msg: '只支持png和jpg格式图片'
				//					});
				//					return;
				//				} else {
				//					var avatarName = '/' + Date.now() + '.' + extName;
				//					var newPath = form.uploadDir + avatarName;
				//					//console.log('blog'+'/'+'ServerJS'+'/'+'pic'+avatarName);  //手动合并路径
				//					fs.renameSync(files.upload0.path, newPath); //重命名
				//				}

				//插入数据库
				//var save_path = '/' + 'blog' + '/' + 'ServerJS' + '/' + 'pic' + avatarName;
				//				console.log(fields.user_id);
				//				console.log(fields.log_content);
				//				console.log(fields.log_date);
				//				console.log(fields.type);
				conn.query("insert into log (log_content,user_id,log_date,log_img) values('" + fields.log_content + "','" + fields.user_id + "','" + fields.log_date + "','" + save_path + "')", function(err, result) {
					if(err) throw err;
					//					console.log(result);
					res.write("发布成功");
					res.end();
				});

			});
		}
		//		var postData = "";
		//		req.on('data', function(data) {
		//			postData += data;
		//			//console.log('接收到的数据为：' + decodeURIComponent(data));
		//		});
		//		req.addListener('end', function() {
		//			var query = qs.parse(postData);
		//		});
	}

	if(req.method.toUpperCase() == 'GET') {

		//这两句用来解决 first argument  must be a string or 	Buffer
		var arg = url.parse(req.url, true).query; //把ajax发送过来的url后面跟的data解析出来
		//var arg = JSON.stringify(arg);                  //stringfy把对象变成字符串

		switch(arg.type) {
			
			
			case "reg":
				console.log(arg.log_username);
				conn.query("insert into user (user_name,user_pass,deposit,goal) values('" + arg.log_username + "','" + arg.log_password + "'0,0)", function(err, result) {
					if(err) throw err;
					console.log(result);
					
					res.write("注册成功");
					res.end();
				});

				break;
				
			//初始化存款表	
//			case "init_accounts_sum":
//			    conn.query("insert into accounts_sum(user_id,deposit,goal) values('" + arg.user_id + "',0,0)" ,function(err,result){
//			    	if(err) throw err;
//					res.write('存款表初始化成功');
//					res.end();
//			    });
//			    break;

			case 'log':
				conn.query("SELECT * from user where user_name = '" + arg.username + "'", function(err, result, fil) {
					if(err) throw err;
					//console.log(result);
					var arg = JSON.stringify(result); //因为前后台只能以字符串的形式传，所以要转换为字符串，前台再转为对象   
					//var propertys = Object.getOwnPropertyNames(data);
					//var temp=new String(result[0].password);
					//              for(var i=0;i<data.length;i++)
					//              {
					//                      da+=data[i].id+" "+data[i].username+" "+data[i].password;
					//              }
					//console.log(result[6].password);
					//console.log("成功了");
					res.write(arg); //这里参数是一个数组，所以会报错
					//res.write("成功了")
					res.end();
				});
				break;
            
            /******
			 *  blog模块
			 * *****/
			case 'publish_blog':
				conn.query("insert into log (log_content,user_id,log_date) values('" + arg.log_content + "','" + arg.user_id + "','" + arg.log_date + "')", function(err, result) {
					if(err) throw err;
					console.log(result);
					res.write("发布成功");
					res.end();
				});
				break;

			case 'create_log':
				conn.query("select a.*,b.com_num from (select log.log_id , log.log_content , log.log_date , log.log_img , user.user_name , user.user_id from log, user where log.user_id = user.user_id) a left join (select log_id, count(*) com_num from comment group by log_id) b on a.log_id = b.log_id;", function(err, result) {
					if(err) throw err;
					var arg = JSON.stringify(result);
					res.write(arg);
					res.end();
				});
				break;

			case 'delete_log_fn':
				var log_id = arg.log_id;
				conn.query("select log_img from log where log.log_id = '" + log_id + "'", function(err, result) {
					if(err) throw err;
					//var arg = JSON.stringify(result);
					var arg = result[0].log_img; //result为数组，result[0]为对象

					conn.query("delete from comment where comment.log_id ='" + log_id + "'", function(err, result) {
						if(err) throw err;
						console.log("已经删除评论数据");

						conn.query("delete from log where log.log_id = '" + log_id + "'", function(err, result) {
							console.log("已经删除日志数据");

							if(arg != "") {
								var img_paths = arg.split(",");
								for(var i = 0; i < img_paths.length; i++) {
									var arr = img_paths[i].split('/');
									var file_paths = 'pic/' + arr[arr.length - 1];
									console.log(file_paths);
									fs.unlink(file_paths, function() {
										if(err) {
											throw err;
										}
										console.log('图片文件删除成功');

									});
								}
							}

						});

					});

					res.write('删除成功');
					res.end();
				});
				break;

				//修改评论加载模式之前的http,弃用
			case 'create_comment':
				conn.query("select user.user_name,log.log_id,log.log_content,comment.comment_content,comment.comment_id from log,comment,user where log.log_id = comment.log_id and comment.user_id = user.user_id;", function(err, result) {
					if(err) throw err;
					var arg = JSON.stringify(result);
					res.write(arg);
					res.end();
				});
				break;

			case 'send_comment':
				conn.query("insert into comment (log_id,user_id,comment_content) values('" + arg.log_id + "','" + arg.user_id + "','" + arg.comment_content + "')", function(err, result) {
					if(err) throw err;
					console.log(result);
					res.write("评论成功");
					res.end();
				});
				break;

				//修改评论加载模式之后的http
			case 'creat_comment_single':
				conn.query("select A.*,B.user_name from comment A,user B where A.log_id='" + arg.log_id + "'and A.user_id = B.user_id;", function(err, result) {
					if(err) throw err;
					var arg = JSON.stringify(result);
					res.write(arg);
					res.end();
				});
				break;
				
				
			/********
			 * accounts模块
			 * ************/	
			 //新增条目
			case 'accounts_push_accountsLis':
			    conn.query("insert into accounts (account_id,user_id,date,matters,amount) values('"+arg.account_id+"','"+arg.user_id+"','"+arg.myDate+"','"+arg.matters+"','"+arg.amount+"')",function(err,result){
			    	if(err) throw err;
			    	console.log(result);
			    	res.write("账本条目增加成功");
			    	res.end();
			    });
			    break;
			    
			//读取条目
			case 'create_accountsLis':
				conn.query("select * from accounts where accounts.user_id = '" + arg.user_id + "'and year(date) = '" + arg.date_year + "' and month(date) = '" + arg.date_month + "'" ,function(err,result){
					if(err) throw err;
					console.log(result);
					var arg = JSON.stringify(result);
					res.write(arg);
					res.end();
				});
				break;
			
			//修改存款
			case 'send_dop':
			    conn.query("update user set deposit = '" +　arg.dop + " 'where user_id = '" + arg.user_id + "'",function(err,result){
			    	if(err) throw err;
			    	console.log(result);
			    	var mes = '修改存款成功';
			    	res.write(mes);
			    	res.end();
			    });
			    break;
			
			//获取存款
			case 'get_dop':
			    conn.query("select user.deposit from user where user_id = '" + arg.user_id + "'" ,function(err,result){
			    	if(err) throw err;
			    	console.log(result);
			    	var arg = JSON.stringify(result);
			    	res.write(arg);
			    	res.end();
			    });
			    break;
			
		    //修改目标
		    case 'modify_goal':
		        conn.query("update user set goal = '" + arg.goal +" 'where user_id = '" + arg.user_id + "'" ,function(err,result){
		        	if(err) throw err;
		        	console.log(result);
		        	var mes = "修改存款成功";
		        	res.write(mes);
		        	res.end();
		        });
		        break;
			
			//获取目标
			case "get_goal":
			    conn.query("select user.goal from user where user_id = '"+ arg.user_id +"'",function(err,result){
			    	if(err)throw err;
			    	console.log(result);
			    	var arg = JSON.stringify(result);
			    	res.write(arg);
			    	res.end();
			    });
			    break;
			
		}
	}

	//console.log(arg.log_username);

}).listen(8686);